package com.dongbo.recorder.screenrecord.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;

import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.adapter.MyPageAdapter;
import com.dongbo.recorder.screenrecord.base.BaseActivity;
import com.dongbo.recorder.screenrecord.bean.TabEntity;
import com.dongbo.recorder.screenrecord.contents.Contents;
import com.dongbo.recorder.screenrecord.ui.fragment.FileFragment;
import com.dongbo.recorder.screenrecord.ui.fragment.HomeFragment;
import com.dongbo.recorder.screenrecord.utils.eventbus.EventMessage;
import com.dongbo.recorder.screenrecord.widget.AgreementDialog;
import com.dongbo.recorder.screenrecord.widget.NonSwipeableViewPager;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.gyf.immersionbar.ImmersionBar;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.dongbo.recorder.screenrecord.Constants;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.ui.fragment.MyFragment;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import butterknife.BindView;

/**
 * @author GuoZi
 * @date :2020/5/5 13:18
 * @description:
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.main_vp)
    NonSwipeableViewPager mainVp;
    @BindView(R.id.main_tab)
    CommonTabLayout mainTab;
//527DEA  BDBDBD
    private String[] mTitles;
    private int[] mIconUnselectIds = {
            R.mipmap.nav_index_cu_icon,
            R.mipmap.nav_video_icon,
            R.mipmap.nav_my_icon};

    private int[] mIconSelectIds = {
            R.mipmap.nav_index_cu_icon2,
            R.mipmap.nav_video_cu_icon,
            R.mipmap.nav_my_cu_icon2};

    private MyPageAdapter myPageAdapter;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    public RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
    private boolean isGree = true;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.color_main)
                .statusBarDarkFont(false)
                .init();

        mTitles = new String[]{
                getResources().getString(R.string.text_home),
                getResources().getString(R.string.btn_videos),
                getResources().getString(R.string.btn_my)};

        mFragments.add(new HomeFragment());
        mFragments.add(new FileFragment());
        mFragments.add(new MyFragment());

        if (myPageAdapter == null) {
            myPageAdapter = new MyPageAdapter(getSupportFragmentManager(), mTitles, mFragments);
        }
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i],
                    mIconSelectIds[i],
                    mIconUnselectIds[i]));
        }
        mainTab.setTabData(mTabEntities);
        mainVp.setAdapter(myPageAdapter);
        mainVp.setOffscreenPageLimit(mTitles.length * 2);
        if (!TextUtils.isEmpty(AppLpds.getInstance().getUserId())) {
            //当用户使用自有账号登录时，可以这样统计：
            MobclickAgent.onProfileSignIn(AppLpds.getInstance().getUserId());
        }
        if (AppLpds.getMySp().getIsFirst()) {
            isGree = false;
            agreementDialog();
        }

//        else {
//            initPermissions();
//        }
    }

    private void agreementDialog() {
        AgreementDialog mDialog = new AgreementDialog(this,
                R.style.recharge_pay_dialog,
                new AgreementDialog.OnDialogEventListener() {

                    @Override
                    public void onClicked(int v) {
                        switch (v) {
                            case 1:
                                WebActivity.start(MainActivity.this,
                                        "用户协议",
                                        Constants.FUWU);

                                break;
                            case 2:
                                WebActivity.start(MainActivity.this,
                                        "隐私政策",
                                        Constants.YINSI);
                                break;
                        }
                    }

                    @Override
                    public void onKonw() {

                        isGree = true;
                        AppLpds.getMySp().setIsFirst(false);
                    }

                    @Override
                    public void onCancel() {
                        System.exit(0);
//                        MainActivity.this.finish();
                    }
                });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
//        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialogInterface) {
//                if (isGree) {
//                    initPermissions();
//                }
//            }
//        });
    }

    private void initPermissions() {
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
//                        Log.d("gstory", "不再询问");
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                    }
                    //最后一个权限校验完成进入首页
                    if (permission.name.equals(Manifest.permission.RECORD_AUDIO)) {

                    }
//                    Log.d("gstory", permission.name);
                });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        mainTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mainVp.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        ImmersionBar.with(MainActivity.this)
                                .fitsSystemWindows(true)
                                .statusBarColor(R.color.color_main)
                                .statusBarDarkFont(false)
                                .init();
                        break;
                    case 1:
//                        ImmersionBar.with(MainActivity.this)
//                                .fitsSystemWindows(true)
//                                .statusBarColor(R.color.white)
//                                .statusBarDarkFont(true)
//                                .init();
                        ImmersionBar.with(MainActivity.this)
                                .fitsSystemWindows(true)
                                .statusBarDarkFont(true)
                                .statusBarColor(R.color.bg)
                                .navigationBarColor(R.color.transparent)
                                .init();
                        break;
                    case 2:
                        ImmersionBar.with(MainActivity.this)
                                .fitsSystemWindows(false)
                                .keyboardEnable(false)
                                .statusBarDarkFont(false)
                                .statusBarColor(R.color.transparent)
                                .navigationBarColor(R.color.transparent)
                                .init();
                        break;
                }
                mainTab.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mainVp.setCurrentItem(0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    /**
     * 接收到推送的事件
     *
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushReceiveEvent(final EventMessage event) {
        //录屏 截屏成功
        if (event.getCode() == Contents.EventType.TAG_SHOT_SUCCESS
                || event.getCode() == Contents.EventType.TAG_RECORD_SUCCESS) {
            boolean isRecordSuecss = (boolean) event.getData();
            if (isRecordSuecss) {
                mainVp.setCurrentItem(1);
            }
        }
    }

    private long firstTime = 0l;

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            showToast(getResources().getString(R.string.tip_exit));
            firstTime = secondTime;
        } else {
            System.exit(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

}
